<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */


class b2c_order_redelivery extends b2c_api_rpc_request
{
    /**
     * 构造方法，不能直接实例化，只能通过调用getInstance静态方法被构造
     * @params null
     * @return null
     */
    public function __construct($app)
    {
        parent::__construct($app);
    }

    /**
     * 最终的克隆方法，禁止克隆本类实例，克隆是抛出异常。
     * @params null
     * @return null
     */
    final public function __clone()
    {
        trigger_error(app::get('b2c')->_("此类对象不能被克隆！"), E_USER_ERROR);
    }

    /**
     * ps ：订单取消完成
     * Time :2015/10/08 20:23:13
     * @author 张艳
     * @param 参数类型
     * @return 返回值类型
    */
    public function generate($sdf, &$controller=null, &$msg='')
    {
        $is_save = true;
        $objOrders = $controller->app->model('orders');
        $arr_data['redelivery_status'] = 2;
        $arr_data['ship_status'] = 5;
        $arr_data['redelivery_memo'] = $sdf['redelivery_memo'];
        $arr_data['order_id'] = $sdf['order_id'];
        if ($sdf['orderInfo']['order_type'] == 'pxfk') {
            //定制平台订单取消状态
            $arr_data['cancel_status'] = 'cancel_ing';
        }
        // $arr_data['status'] = 'dead';
        //2015-9-16 by 张艳,在保存前，先同步到jxc,同步成功后才保存到本地
        if ($sdf['pay_status']) {
            $r=$this->_get_redelivery_data($sdf);
            if($r['rsp']===false) {
                header('Content-Type:text/jcmd; charset=utf-8');
                echo '{error:"'.$r['data']['msg'].'",_:null}';
                exit;
            }
        }
        $objOrders->save($arr_data);
        $this->request($arr_data);
        // $sdf_order = $objOrders->dump($sdf['order_id'], '*');
        if ($sdf['orderInfo']['order_type'] != 'pxfk') {
            //更新库存
            $is_unfreeze = $this->unfreezeGoods($sdf['order_id']);
        }
        $order_items_model=app::get('b2c')->model('order_items');
        $order_madanIds=$order_items_model->getList('madan_ids,peihuoCodes',array('order_id'=>$sdf['order_id']));
        //当没有码单的时候不需要同步jxc
        foreach ($order_madanIds as  $value) {
            if(trim($value['madan_ids'])){
                $value['madan_ids']!='' && $madanIds.=','.$value['madan_ids'];
                //2015-10-28 by jiang 如果选择大货的配货单 则同步配货单
            }
            if (trim($value['peihuoCodes'])) {
                $value['peihuoCodes']!='' && $peihuoCodes.=','.$value['peihuoCodes'];
            }
        }
        if($madanIds){
             $r=$this->_get_order_data($madanIds,$peihuoCodes);
             if($r['rsp']===false) {
                $msg = $r['data']['msg'];
                return false;
             }
        }
        $log_text[] = array(
            'txt_key'=>'订单取消发货',
            'data'=>array(
            ),
        );
        $log_text = serialize($log_text);
        $objorder_log = $this->app->model('order_log');
        $sdf_order_log = array(
            'rel_id' => $sdf['order_id'],
            'op_id' => $sdf['op_id'],
            'op_name' => $sdf['opname'],
            'alttime' => time(),
            'bill_type' => 'order',
            'behavior' => 'redelivery',
            'result' => 'SUCCESS',
            'log_text' => $log_text,
        );
        $log_id = $objorder_log->save($sdf_order_log);
        //判断是否有使用优惠券,有则退回优惠券
        $coupon_ref = app::get('couponlog')->model('order_coupon_ref');
        $couponInfo = $coupon_ref->getRow('*',array('order_id'=>$sdf['order_id']));
        if($couponInfo){
            $obj_coupon = kernel::single("b2c_coupon_order");
            $obj_coupon->cancel_c($couponInfo);
        }
        return $is_save;
    }
    /**
     * ps ：同步处理数据，注意以下格式不能变化
     * Time :2015/10/08
     * @author 张艳
     * @param 参数类型
     * @return 返回值类型
    */
    function _get_redelivery_data($sdf){
        //订单主表
        $params['orderCode']=$sdf['order_id'];
        $params['isdelivery_desc']="创建人：".$sdf['opname']."; 原因：".$sdf['redelivery_memo'];
        $params['order_type']=$sdf['orderInfo']['order_type'];
        $post = array(
            'method'=>'order.isdelivery',
            'params'=>$params,
        );
        $erp_caller_obj = kernel::service('apioubao.rpc_erp_request');
        $result = $erp_caller_obj->call_api_oubao($post);
        $r = json_decode($result,true);
        return $r;
    }
    /**
     * ps ：取消订单同步到erp
     * Time :2015/09/18 10:58:38
     * @author 张艳
     * @param 参数类型
     * @return 返回值类型
    */
    function _get_order_data($madan_ids,$peihuoCodes){
        $madan_ids=join(',',array_filter(explode(',',$madan_ids)));
        $params['madanIds']= $madan_ids;
        $params['peihuoCodes']= $peihuoCodes;
        $params['status']='active';
        $post = array(
            'method'=>'peihuo.lock',
            'params'=>$params
        );
        $erp_caller_obj = kernel::service('apioubao.rpc_erp_request');
        $result = $erp_caller_obj->call_api_oubao($post);
        $r = json_decode($result,true);
        return $r;
    }
    private function unfreezeGoods($order_id)
    {
        $is_unfreeze = true;
        $subsdf = array('order_objects'=>array('*',array('order_items'=>array('*',array(':products'=>'*')))));
        $sdf_order = $this->app->model('orders')->dump($order_id, 'order_id,status,pay_status,ship_status', $subsdf);

        // 所有的goods type 处理的服务的初始化.
        $arr_service_goods_type_obj = array();
        $arr_service_goods_type = kernel::servicelist('order_goodstype_operation');
        foreach ($arr_service_goods_type as $obj_service_goods_type)
        {
            $goods_types = $obj_service_goods_type->get_goods_type();
            $arr_service_goods_type_obj[$goods_types] = $obj_service_goods_type;
        }

        $objGoods = $this->app->model('goods');
        foreach($sdf_order['order_objects'] as $k => $v)
        {
            if ($v['obj_type'] != 'goods' && $v['obj_type'] != 'gift')
            {
                foreach( kernel::servicelist('b2c.order_store_extends') as $object ) {
                    if( $object->get_goods_type()!=$v['obj_type'] ) continue;
                    $obj_extends_store = $object;
                    if ($obj_extends_store)
                    {
                        $obj_extends_store->store_change($v, 'cancel');
                    }
                }
                continue;
            }

            foreach ($v['order_items'] as $arrItem)
            {
                if ($arrItem['item_type'] == 'product')
                    $arrItem['item_type'] = 'goods';
                $arr_params = array(
                    'goods_id' => $arrItem['products']['goods_id'],
                    'product_id' => $arrItem['products']['product_id'],
                    'quantity' => $arrItem['quantity'],
                );
                $str_service_goods_type_obj = $arr_service_goods_type_obj[$arrItem['item_type']];
                $is_unfreeze = $str_service_goods_type_obj->unfreezeGoods($arr_params);
            }
        }

        return $is_unfreeze;
    }

}
